﻿# -*- coding:utf-8 -*-
#
# склад
#
import datetime
from django.shortcuts import render_to_response
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import permission_required
from django.template import RequestContext, Context
from django.core.urlresolvers import reverse
from django.db.models import Sum, Count


from sklad.forms import CategoryForm, PartForm 
from sklad.models import Category, Part, Document, DocumentReceipt, DocumentDelivery, Unit, Waybill


from sklad.contextprocessors import category_proc



@login_required
@permission_required('sklad.view_part')
def view(request, catid):
    category = get_object_or_404(Category, id=catid)
    # collaps
    try:
        collaps = int(request.GET.__getitem__('collaps'))
        if int(catid) in request.session["expanded_catid"]:
            request.session["expanded_catid"].remove(int(catid))
        if "prev_request_path" in request.session:
            return HttpResponseRedirect(request.session["prev_request_path"])
    except KeyError, ValueError:
        pass
    # expand    
    try:
        expand = int(request.GET.__getitem__('expand'))
        if int(catid) not in request.session["expanded_catid"]:
            request.session["expanded_catid"].append(int(catid))  
        if "prev_request_path" in request.session:
            return HttpResponseRedirect(request.session["prev_request_path"])
    except KeyError, ValueError:
        pass
    # select category
    request.session["current_category"] = int(catid)    
    sub_categories = Category.objects.filter(parent=request.session["current_category"])
    if "all" in request.GET:
        qs = Waybill.objects.filter(part__category__in=sub_categories)
    else:        
        qs = Waybill.objects.filter(part__category=category)
    qs.query.group_by = ['part_id']
    partlist = qs.annotate(Sum("count")).order_by("part")  
   
    pnl = Part.objects.filter(category=category)
    pl = [item.part.id for item in list(partlist)]
    part_noreg_list = pnl.exclude(id__in=pl)
    
    context = Context({
      'category':category,
      'partlist': partlist,
      'part_noreg_list':part_noreg_list,
      'sub_categories':sub_categories,
    })
    return render_to_response('sklad/category_part.html', context,  context_instance=RequestContext(request, processors=[category_proc]))



@login_required
@permission_required('sklad.change_category')
def edit(request, catid):
    cat_inst = Category.objects.get(id=catid)
    if request.method == 'POST':
        form = CategoryForm(request.POST, request.FILES,  instance=cat_inst)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            category.save()
            return HttpResponseRedirect( reverse('category_view', args=[(request.session["current_category"])]) )
    else:
        form = CategoryForm(instance=cat_inst)
    return render_to_response('sklad/form_category_edit.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))





@login_required
@permission_required('sklad.add_category')
def create(request, catid):
    if request.method == 'POST':
        form = CategoryForm(request.POST, request.FILES)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            request.session["current_category"] = category.id
            category.save()
            return HttpResponseRedirect(reverse('category_view', args=[category.id]))
    else:
        form = CategoryForm(initial={'parent': catid})
    return render_to_response('sklad/form_category_add.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))


@login_required
@permission_required('sklad.add_category')
def create_root(request):
    if request.method == 'POST':
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save(commit=False)
            category.user = request.user
            request.session["current_category"] = category.id
            category.save()
            return HttpResponseRedirect(reverse('category_view', args=[category.id]))
    else:
        form = CategoryForm(initial={'parent': None})
    return render_to_response('sklad/form_category_add_root.html', locals(), context_instance=RequestContext(request, processors=[category_proc]))





@login_required
@permission_required('sklad.delete_category')
def delete(request, item):
    pass
    
   




